import 'package:sinosheets/utils/favorite/flash_sale_product_model.dart';
import 'package:sinosheets/utils/favorite/normal_product_model.dart';
import 'package:sinosheets/utils/isar_manager.dart';
import 'package:isar/isar.dart';
import 'dart:async';

class IsarProductService {
  static final IsarProductService _instance = IsarProductService._internal();
  factory IsarProductService() => _instance;

  Isar? _isar;
  bool _isInitialized = false;

  IsarProductService._internal();

  Future<void> init() async {
    // 如果已经初始化，直接返回
    if (_isInitialized && _isar != null) {
      return;
    }

    await IsarManager().init();
    _isar = IsarManager().isar;
    _isInitialized = true;
    print('IsarProductService: 初始化成功');
  }

  // 确保Isar已初始化
  void _ensureInitialized() {
    if (!_isInitialized || _isar == null) {
      throw Exception('IsarProductService未初始化，请先调用init()方法');
    }
  }

  // ==================== FlashSaleProduct 收藏 ====================
  Future<void> addFavoriteFlashSaleProduct(Map<String, dynamic> productData) async {
    _ensureInitialized();
    await _isar!.writeTxn(() async {
      final product = FlashSaleProductModel()
        ..productId = productData['id']?.toString() ?? ''
        ..inId = productData['inId']?.toString() ?? ''
        ..productName = productData['productName']?.toString() ?? ''
        ..productImage = productData['img']?.toString() ?? ''
        ..price = (productData['price'] ?? 0.0).toDouble()
        ..crossedPrice = (productData['crossedPrice'] ?? 0.0).toDouble()
        ..symbol = productData['symbol']?.toString() ?? ''
        ..detailUrl = productData['detailUrl']?.toString() ?? ''
        ..category = productData['category']?.toString() ?? ''
        ..createTime = DateTime.now()
        ..updateTime = DateTime.now();
      await _isar!.flashSaleProductModels.put(product);
    });
  }

  Future<void> removeFavoriteFlashSaleProduct(String productId) async {
    _ensureInitialized();
    await _isar!.writeTxn(() async {
      await _isar!.flashSaleProductModels.filter().productIdEqualTo(productId).deleteAll();
    });
  }

  Future<List<FlashSaleProductModel>> getFavoriteFlashSaleProducts() async {
    _ensureInitialized();
    return await _isar!.flashSaleProductModels.where().findAll();
  }

  Future<bool> isFlashSaleProductFavorite(String productId) async {
    _ensureInitialized();
    final product = await _isar!.flashSaleProductModels.filter().productIdEqualTo(productId).findFirst();
    return product != null;
  }

  // ==================== NormalProduct 收藏 ====================
  Future<void> addFavoriteNormalProduct(Map<String, dynamic> productData) async {
    _ensureInitialized();
    await _isar!.writeTxn(() async {
      final product = NormalProductModel()
        ..productId = productData['id']?.toString() ?? ''
        ..inId = productData['inId']?.toString() ?? ''
        ..itemName = productData['itemName']?.toString() ?? ''
        ..productImage = productData['img']?.toString() ?? ''
        ..price = (productData['price'] ?? 0.0).toDouble()
        ..crossedPrice = (productData['crossedPrice'] ?? 0.0).toDouble()
        ..symbol = productData['symbol']?.toString() ?? ''
        ..detailUrl = productData['detailUrl']?.toString() ?? ''
        ..category = productData['category']?.toString() ?? ''
        ..createTime = DateTime.now()
        ..updateTime = DateTime.now();
      await _isar!.normalProductModels.put(product);
    });
  }

  Future<void> removeFavoriteNormalProduct(String productId) async {
    _ensureInitialized();
    await _isar!.writeTxn(() async {
      await _isar!.normalProductModels.filter().productIdEqualTo(productId).deleteAll();
    });
  }

  Future<List<NormalProductModel>> getFavoriteNormalProducts() async {
    _ensureInitialized();
    return await _isar!.normalProductModels.where().findAll();
  }

  Future<bool> isNormalProductFavorite(String productId) async {
    _ensureInitialized();
    final product = await _isar!.normalProductModels.filter().productIdEqualTo(productId).findFirst();
    return product != null;
  }

  // ==================== 通用操作 ====================
  Future<void> clearAllFavorites() async {
    _ensureInitialized();
    await _isar!.writeTxn(() async {
      await _isar!.flashSaleProductModels.clear();
      await _isar!.normalProductModels.clear();
    });
  }

  /// 关闭数据库连接
  Future<void> close() async {
    if (_isar != null && _isInitialized) {
      await _isar!.close();
      _isar = null;
      _isInitialized = false;
    }
  }
}
